﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;

namespace Xmhouse.Passport
{

    public partial class WebLogin : System.Web.UI.Page
    {
       
        private  Xmhouse.Config.AppConfig.AppConfigInfo XCAC = Xmhouse.Config.AppConfig.load();
        bool bIsAjax = false;
        string sSaveState = "0";
        protected void Page_Load(object sender, EventArgs e)
        {
            string sUserName = Request.Form["XmhouseUserName"];         //用户名
            string sPassWord = Request.Form["XmmhousePassword"];        //密码
            string sValidCode = Request.Form["XmhouseValidCode"];       //填写的验证码
            string sActiveCode = Request.Form["ActiveCode"];            //填写的验证码
            string sReturnUrl = Request.Form["toUrl"];                  //登录成功转向
            sSaveState = Request.Form["SaveState"];              //保存状态
            string sIsAjax = Request.Form["IsAjax"];                    // 是否AJAX
            bIsAjax = (string.IsNullOrEmpty(sIsAjax) || (sIsAjax != "1")) ? false : true; //是否AJAX
            

            if (!(string.IsNullOrEmpty(sUserName) && string.IsNullOrEmpty(sPassWord)))
            {

                #region 验证码处理
                //if (sValidCode != null && sValidCode.Length == 4)
                //{
                //    if (Request.Cookies["CheckCode"] == null)
                //    {
                //        Response.Write(jsAlert(500,"浏览器不支持Cookie或是未生成验证码!", 1, null));
                //        Response.End();
                //    }
                //    string strCode = Request.Cookies["CheckCode"].Value;
                //    if (string.IsNullOrEmpty(strCode) || sValidCode != strCode)
                //    {
                //        Response.Write(jsAlert(403,"提示:请输入正确的验证码!", 1, null));
                //        Response.End();
                //    }
                //}
                //else
                //{
                //    Response.Write(jsAlert(403,"提示:请输入正确的验证码!", 1, null));
                //    Response.End();
                //}
                #endregion

                sUserName = sUserName.Trim();

                if (string.IsNullOrEmpty(sUserName) || sUserName.Length < 1)
                {
                    Response.Write(jsAlert(403,"提示:请输入正确的用户名（至少1位）!", 1, null));
                    Response.End();
                }

                if (string.IsNullOrEmpty(sPassWord) && sPassWord.Length < 3)
                {
                    Response.Write(jsAlert(403,"提示:请输入正确的密码（至少三位）!", 1, null));
                    Response.End();
                }
                doLogin(sUserName, sPassWord, sReturnUrl, sActiveCode);
            }

        }
        protected int doLogin(string sUserName, string sPassWord, string sReturnUrl, string sActiveCode)
        {
            Passport Pa = new Passport();
            int iStaus;
            try
            {
                string strIp = Common.GetRealIP();
                PassportManage PaM = new PassportManage();
                iStaus = PaM.Login(sUserName, sPassWord, strIp, SessionID(), sActiveCode, ref Pa);
                string ErrInfo = PaM.ErrInfo;
                PaM.Dispose();
                PaM = null;
                switch (iStaus)
                {
                    case -2:
                        Response.Write(jsAlert(-2,"你的激活码出错，无法激活！", 1, null));
                        return iStaus;
                    case -1:
                        Response.Write(jsAlert(-1,"您的用户名或密码错误！", 1, null));
                        return iStaus;
                    case 0:
                        Response.Write(jsAlert(0,"您的账号还未激活！", 1, null));
                        return iStaus;

                    case 2://冻结

                        Response.Write(jsAlert(2, "该用户已被冻结！冻结时间！", 1, null));
                        return iStaus;
                    case 4:
                        Response.Write(jsAlert(4, "您的帐号已经过期了，请联系客服续费！！！", 1, null));

                        return iStaus;
                    case 1:

                        #region 登录成功

                        //产生令牌
                        string tokenValue = Pa.Token;

                        //tokenCookie.Domain = "passport.com";
                        //Response.AppendCookie(tokenCookie);

                        //产生主站凭证
                        //object info = true;

                        string PaValue = Newtonsoft.Json.JavaScriptConvert.SerializeObject(Pa);
                        int timeout = (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["timeout"]))?20:int.Parse(System.Configuration.ConfigurationManager.AppSettings["timeout"]);
                        
                        CacheManager cm  = new CacheManager();
                        if (!cm.TokenInsert(tokenValue, PaValue, timeout, Request.ServerVariables["HTTP_REFERER"], strIp, sUserName,Pa.UserID ,Pa.InitModel ))
                        {
                            /*无法写入数据库操作*/
                            Response.Write(jsAlert(500,cm.ErrInfo, 1, null));
                            return iStaus;
                        }
                        else
                        {
                            /*写入Cookie令牌*/
                            //string tokenValue = this.getGuidString();
                            HttpCookie tokenCookie = new HttpCookie(XCAC.PassportTokenCookie);
                            tokenCookie.Values.Add("Value", tokenValue);
                            if (!string.IsNullOrEmpty(sSaveState) && sSaveState == "1")
                                tokenCookie.Expires = DateTime.Now.AddDays(30); //设定过期时间
                            Response.AppendCookie(tokenCookie);
                        }
                        cm.Dispose();
                        cm = null;

                        //带主站令牌跳转回分站
                        if (!string.IsNullOrEmpty(sReturnUrl))
                        {
                            if (!sReturnUrl.ToLower().StartsWith("javascript:"))
                            {
                                Response.Redirect(getTokenURL(sReturnUrl, tokenValue));
                            }
                            else
                            {
                                Response.Write(jsAlert(1, "你已经登录成功！", 1, sReturnUrl.Replace("javascript:", "")));
                            }
                                                        
                        }
                        else if(string.IsNullOrEmpty(Request.ServerVariables["HTTP_REFERER"]) || Request.ServerVariables["HTTP_REFERER"] == Request.Url.AbsoluteUri)
                        {
                            Response.Write(jsAlert(1,"你已经登录成功！", 1, null));
                        }
                        else
                        {
                            Response.Redirect(getTokenURL(Request.ServerVariables["HTTP_REFERER"],tokenValue));
                        }

                        #endregion

                        return iStaus;
                    default:
                        Response.Write(jsAlert(500, ErrInfo, 1, null));
                        return iStaus;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return 500;
            }

        }
        public string SessionID()
        {
            string SessionCookieName = "_Xmhouse_SessionId_";
            if (Request.Cookies[SessionCookieName]==null||string.IsNullOrEmpty(Request.Cookies[SessionCookieName].Value))
            {
                HttpCookie cookieSession = new HttpCookie(SessionCookieName, Session.SessionID);
                Response.AppendCookie(cookieSession);
            }
            return Request.Cookies[SessionCookieName].Value;
        }

        /// <summary>
        /// 产生绝对唯一字符串，用于令牌
        /// </summary>
        /// <returns></returns>
        private string getGuidString()
        {
            return Guid.NewGuid().ToString().ToLower();
        }

        public void Alert(string strAlert, int type, string GoPage)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", jsAlert(strAlert, type, GoPage));
        }

        public void Alert(string strAlert)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "提示", jsAlert(strAlert, 0, null));
        }

        #region javascript 提示功能
        /// <summary>
        /// javascript 提示功能
        /// </summary>
        /// <param name="strAlert">提示内容</param>
        /// <param name="type">0不操作,1退回 ,2转向页面,3关闭窗口,4刷新父级窗口关闭子窗口</param>
        /// <param name="GoPage">type=2 的转向页面</param>
        /// <returns>javascript 提示构成的字符串</returns>
        private string jsAlert(int State,string strAlert, int type, string GoPage)
        {
            if (bIsAjax)
            {
                //return string.Concat(State, ",", strAlert);
                return jsAlert(strAlert, 0, GoPage);
            }
            else
            {
                return jsAlert(strAlert, type, GoPage);
            }
        }
        private string jsAlert(string strAlert, int type, string GoPage)
        {
            string temp;
            temp = "<script type='text/javascript'>";
            temp += "alert('" + strAlert + "');";
            switch (type)
            {
                case 0:
                    break;
                case 1:
                    temp += "history.back();";
                    break;
                case 2:
                    temp += "location.href='" + GoPage + "';";
                    break;
                case 3:
                    temp += "window.close();";
                    break;
                case 4:
                    temp += "window.opener.location.reload();";
                    temp += "window.close();";
                    break;
                default:
                    temp += "";
                    break;
            }
            temp += "</script>";
            return temp;
        }
        #endregion

        /// <summary>
        /// 获取带令牌请求的URL
        /// 在当前URL中附加上令牌请求参数
        /// </summary>
        /// <returns></returns>
        private string getTokenURL()
        {
            string url = Request.Url.AbsoluteUri;
            Regex reg = new Regex(@"^.*\?.+=.+$");
            if (reg.IsMatch(url))
                url += "&Token=$Token$";
            else
                url += "?Token=$Token$";

            return string.Concat(XCAC.PassportGetTokenPage, "?", "toUrl=" + Server.UrlEncode(url));
        }

        /// <summary>
        /// 获取带令牌请求的URL
        /// 在当前URL中附加上令牌请求参数
        /// </summary>
        /// <returns></returns>
        private string getTokenURL(string toUrl,string TokenValue)
        {
            toUrl = Regex.Replace(toUrl, @"(\?|&)Token=.*", "", RegexOptions.IgnoreCase);
            string sSessionId = Request.Form["SessionId"];
            Regex reg = new Regex(@"^.*\?.+=.+$");
            if (reg.IsMatch(toUrl))
                toUrl += string.Concat("&SaveState=", sSaveState, "&Token=", TokenValue);
            else
                toUrl += string.Concat("?SaveState=", sSaveState, "&Token=", TokenValue);
            return toUrl;
        }
    }
}